/*
 * @Author: duapple
 * @Date: 2021-09-30 16:42:02
 * @LastEditTime: 2022-03-10 10:14:11
 * @LastEditors: duapple
 * @Description: Add description
 * @FilePath: \go_clang_format\test_copy.c
 * Copyright (c) 2011 duapple - All rights reserved.
 */
#include "sl_uart_dfu.h"
#include "user_cmd.h"
#include <stdio.h>

#define LOG_INFO(...) printf(__VA_ARGS__)

void uart_dfu_progress_handler(uint32_t progress)
{
    LOG_INFO("\r%d%%", progress);
}

int main(int argc, char *argv[])
{
    if (argc < 3)
    {
        return 1;
    }

    /* 1. 初始化服务，ncp target通信依赖*/
    int ret = sl_uart_dfu_init(argv[2], 115200);
    if (ret)
    {
        LOG_INFO("uart dfu init failed: %d\n", ret);
        return;
    }

    /*-------------------------------------------------------------------------------------------------------*
     *    重启到app，如果失败，则target已经处于boot（由于升级失败导致），因此不调用获取版本的接口
     *-------------------------------------------------------------------------------------------------------*/
    dev_info_t devInfo;
    sl_bt_dfu_reset(0);
    bool is_in_boot = sl_wait_system_booting(5);
    if (is_in_boot)
    {

        /* 2. 获取ncp target版本信息，确定是否升级*/
        memset(&devInfo, 0, sizeof(devInfo));
        ret = get_ncp_target_dev_info(&devInfo);
        if (ret)
        {
            LOG_INFO("get ncp target dev info failed: %d\n", ret);
            sl_uart_dfu_deinit();
            return;
        }
        LOG_INFO("NCP TARGET: NCP: 0X%02X, SW: 0X%02X, HW: 0X%02X\n", devInfo.ncp_ver, devInfo.software_ver,
                 devInfo.hardware_ver);

        if (devInfo.ncp_ver != NCP_VERSION || devInfo.software_ver < 0x01)
        {
            LOG_INFO("The upgrade requirements are not met.");
            sl_uart_dfu_deinit();
            return 0;
        }
    }

    /* 3. 执行升级 */
    ret = sl_uart_dfu_start(argv[1], uart_dfu_progress_handler);
    if (ret)
    {
        LOG_INFO("\nuart dfu failed: %d\n", ret);
        sl_uart_dfu_deinit();
        return 0;
    }

    /* 4. 升级结束后，等待ncp target重启 */
    bool system_booting = sl_wait_system_booting(5);

    /* 5. 设备重启成功后，获取设备的版本信息，确认是否升级成功 */
    dev_info_t devInfoNew;
    if (system_booting)
    {
        system_booting = false;
        memset(&devInfoNew, 0, sizeof(devInfoNew));
        ret = get_ncp_target_dev_info(&devInfoNew);
        if (ret)
        {
            LOG_INFO("get ncp target dev info failed: %d\n", ret);
        }
        else
        {
            LOG_INFO("NCP TARGET: NCP: 0X%02X, SW: 0X%02X, HW: 0X%02X\n", devInfoNew.ncp_ver, devInfoNew.software_ver,
                     devInfoNew.hardware_ver);
            if (devInfoNew.software_ver > devInfo.software_ver)
            {
                LOG_INFO("dfu success\n");
            }
        }
    }
    else
    {
        LOG_INFO("dfu failed\n");
    }

    /* 6. 退出升级 */
    sl_uart_dfu_deinit();

    return 0;
}